﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CLFramework.Infrastructure.Validation
{
    public class ModelResult<T> : ModelResult
    {
        public ModelResult(ValidationStateDictionary validationState)
            : base(validationState)
        {
        }

        public ModelResult(T result, ValidationStateDictionary validationState)
            : base(validationState)
        {
            Item = result;
        }

        public ModelResult(T result, string validationKey, string validationMessageKey
            , string validationMessage, params object[] validationMessageParameters)
        {
            ValidationState state = new ValidationState();
            ValidationStateDictionary validationState = new ValidationStateDictionary(typeof(T), state);
            state.AddValidationError(result, validationKey, validationMessageKey, validationMessage, validationMessageParameters);
           
            Item = result;
            ValidationState = validationState;
            IsValid = validationState == null || validationState.IsValid;
        }

        /// <summary>
        /// <remarks>
        /// Changed by Lance 2010-2-3, we need update the IsValid property after adding
        /// or merging a new ValidationState
        /// </remarks>
        /// </summary>
        /// <param name="state"></param>
        public void Add(ValidationState state)
        {
            Type type = typeof(T);
            if (!ValidationState.ContainsKey(type))
                ValidationState.Add(type, state);
            else
                ValidationState[type].Merge(state);

            IsValid = ValidationState == null || ValidationState.IsValid;
        }

        public T Item { get; private set; }
    }

}
